package com.yhc.order.server.interceptor;

import com.yhc.common.dto.UserCacheInfo;
import com.yhc.order.server.exception.ErrorCodeEnum;
import com.yhc.order.server.consts.RequestHeader;
import com.yhc.order.server.exception.OrderServiceException;
import com.yhc.order.server.plugin.RedisService;
import com.yhc.order.server.service.IUserCacheService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 用户校验
 */
@Slf4j
@Configuration
public class UserInterceptor implements HandlerInterceptor {

    @Value("#{'${no.login.uri}'.split(',')}")
    List<String> noLoginUri;

    @Autowired
    RedisService redisService;

    @Autowired
    IUserCacheService userCacheService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws OrderServiceException {
        validHeader(request);
        return true;
    }

    /**
     * 请求头校验
     *
     * @param request
     */
    private void validHeader(HttpServletRequest request) {
        String requestId = request.getHeader(RequestHeader.REQUEST_ID);
        String userToken = request.getHeader(RequestHeader.USER_TOKEN);
        String txTime = request.getHeader(RequestHeader.TX_TIME);

        log.info("# request headers: requestId:{}, userToken:{}, txTime:{}", requestId, userToken, txTime);

        if (StringUtils.isBlank(requestId)) {
            throw new OrderServiceException(ErrorCodeEnum.EXCEPTION_REQUIRED_PARAMS_NO_REQUEST_ID);
        }
        if (StringUtils.isBlank(txTime)) {
            throw new OrderServiceException(ErrorCodeEnum.EXCEPTION_REQUIRED_PARAMS_NO_TX_TIME);
        }

        // 校验登录态
        String requestsUri = request.getRequestURI();
        log.info("# request uri : {}", requestsUri);
        if (noLoginUri.contains(requestsUri)) {
            return;
        }
        if (StringUtils.isBlank(userToken)) {
            throw new OrderServiceException(ErrorCodeEnum.EXCEPTION_USER_NO_LOGIN);
        } else {
            if (redisService.exists(userToken)) {
                UserCacheInfo user = redisService.get(userToken, UserCacheInfo.class);
                userCacheService.setUser(user);
            } else {
                throw new OrderServiceException(ErrorCodeEnum.EXCEPTION_USER_NO_LOGIN);
            }
        }

    }

}
